
const { validateFields } = require('../public/util.js')
const { successMsg, errorMsg,page,roomState } = require('../public/constant.js')
const {executeTransaction}=require('../mysql/public.js')
const pool = require('../mysql/mysql.js');
const express = require('express');
const router = express.Router();
const multer = require('multer');
const upload = multer();

const tableName='order_list'

const getField=(tableName,fieldList)=>{
  var field=''
  for(var i in fieldList){
    field+=`${tableName}.${fieldList[i]},`
  }
  field=field.slice(0,-1)
  return field
}
let guestFieldList=['guest_name','phone','reside_date','checkout_date','guest_num','id_card']
var guestField=getField('guest',guestFieldList)
let commonSql=`SELECT ${tableName}.*,${guestField} FROM ${tableName}
left join guest on ${tableName}.guest_id=guest.guest_id `

// 修改
router.post('/Edit', upload.none(), validateFields([
  { field: 'isComplete', noEmpty: true, validType: 'number' },
  { field: 'orderId', noEmpty: true, validType: 'string' },
]), (req, res) => {
  const { isComplete,orderId } = req.body;
  executeTransaction({pool,res,queries:[
    {
      sql:`SELECT * FROM ${tableName} WHERE order_id=? and is_delete=0`,
      params:[orderId],
      stopFlag:(result)=>!result.length,
      stopEvent:()=>{res.status(200).send(errorMsg('没有该订单'))},
      successEvent:()=>{},
    },
    {
      sql:`UPDATE ${tableName} SET is_complete=? WHERE order_id=?`,
      params:[isComplete,orderId],
    },
    {
      sql:`select * from ${tableName} where order_id=?`,
      params:[orderId],
    },
    {
      sql:`update room set room_state_id=? where room_id=?`,
      params:[roomState.empty],
      modifyParamsEvent:(params,result)=>{
        params.push(result[0].room_id)
        return params
      },
      successEvent:()=>{res.status(200).send(successMsg())},
    }
  ]})
});



// 查询数据
router.get('/List', (req, res) => {
  pool.query(`${commonSql} where ${tableName}.is_delete=0 ORDER BY ${tableName}.create_time DESC`, (err, result) => {
    if (err){
      return res.status(500).send(errorMsg('数据库错误'));
    }
    var r = [...result]
    res.status(200).send(successMsg(r));
  });
});
// 查询数据
router.post('/PageList',upload.none(), (req, res) => {
  let {pageSize,pageIndex,roomTypeId,isComplete,roomNumber}=req.body
  pageSize=pageSize||10
  pageIndex=pageIndex||1
  let conditionSql=''
  const arr=[pageSize,(pageIndex-1)*pageSize]
  let conditionArr=[]
  if(roomTypeId){
    conditionSql+=` and ${tableName}.room_type_id=?`
    conditionArr.push(roomTypeId)
    arr.push(roomTypeId)
  }
  if([0,1].includes(isComplete)){
    conditionSql+=` and ${tableName}.is_complete=?`
    conditionArr.push(isComplete)
    arr.push(isComplete)
  }
  if(roomNumber){
    conditionSql+=` and ${tableName}.room_number=?`
    conditionArr.push(roomNumber)
    arr.push(roomNumber)
  }
  const sql=`${commonSql} 
  WHERE ${tableName}.is_delete = 0${conditionSql} ORDER BY ${tableName}.create_time DESC LIMIT ? OFFSET ?; 
  SELECT COUNT(*) FROM ${tableName} WHERE ${tableName}.is_delete = 0${conditionSql}`
  pool.query(sql,[...conditionArr,...arr],(err, result) => {
    if (err){
      console.log(err)
      return res.status(500).send(errorMsg('数据库错误'));
    }
    res.status(200).send(successMsg(page({data:result[0],total:result[1][0]['COUNT(*)'],pageIndex})));
  });
});
// 获取某一个
router.post('/GetOne', upload.none(), validateFields([
  { field: 'orderId', noEmpty: true, validType: 'number' },
]), (req, res) => {
  const { orderId } = req.body
  const sql = `${commonSql} WHERE ${tableName}.order_id=? and ${tableName}.is_delete=0`
  pool.query(sql, [orderId], (err, result) => {
    if (err){
      return res.status(500).send(errorMsg('数据库错误'));
    }
    var r = [...result]
    res.status(200).send(successMsg(r))
  })
});
// 删除
router.get('/Delete', (req, res) => {
  const { orderId } = req.query
  if (!orderId) {
      return res.status(200).send(errorMsg('orderId'));
  }
  executeTransaction({pool,res,queries:[
    {
      sql:`SELECT * FROM ${tableName} WHERE order_id=?`,
      params:[orderId],
      stopFlag:(result)=>!result.length,
      stopEvent:()=>{res.status(200).send(errorMsg('无效id'))},
      successEvent:()=>{}
    },
    {
      sql:`UPDATE ${tableName} SET is_delete=1 WHERE order_id=?`,
      params:[orderId],
      stopFlag:false,
      successEvent:()=>{res.status(200).send(successMsg('操作成功'))}
    }
  ]})
});
module.exports = router;